<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>抽奖系统管理后台</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --sidebar-width: 250px;
            --header-height: 60px;
            --primary-color: #4a90e2;
            --secondary-color: #357abd;
            --text-color: #333;
            --light-bg: #f8f9fa;
            --border-color: #e9ecef;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: var(--light-bg);
            color: var(--text-color);
        }

        /* 侧边栏样式 */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, #2c3e50 0%, #1a252f 100%);
            padding-top: var(--header-height);
            z-index: 1000;
            transition: all 0.3s ease;
        }

        .sidebar-sticky {
            height: calc(100vh - var(--header-height));
            overflow-y: auto;
            padding: 1rem 0;
        }

        .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 0.8rem 1.5rem;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            color: #fff;
            background: rgba(255, 255, 255, 0.1);
        }

        .nav-link.active {
            color: #fff;
            background: rgba(255, 255, 255, 0.2);
            border-left: 4px solid var(--primary-color);
        }

        .nav-link i {
            width: 20px;
            margin-right: 10px;
            font-size: 1.1rem;
        }

        /* 顶部导航栏样式 */
        .navbar {
            position: fixed;
            top: 0;
            right: 0;
            left: var(--sidebar-width);
            height: var(--header-height);
            background: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, .08);
            z-index: 1000;
            padding: 0 1.5rem;
        }

        .navbar-brand {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--text-color);
        }

        /* 主内容区域样式 */
        .main-content {
            margin-left: var(--sidebar-width);
            padding: calc(var(--header-height) + 1.5rem) 1.5rem 1.5rem;
            min-height: 100vh;
        }

        .content-wrapper {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, .05);
            padding: 1.5rem;
        }

        /* 表格样式 */
        .table {
            margin-bottom: 0;
        }

        .table th {
            font-weight: 600;
            background: var(--light-bg);
            border-bottom: 2px solid var(--border-color);
        }

        .table td {
            vertical-align: middle;
        }

        /* 按钮样式 */
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 4px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-primary:hover {
            background: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .btn-danger {
            background: #dc3545;
            border-color: #dc3545;
        }

        .btn-danger:hover {
            background: #c82333;
            border-color: #bd2130;
        }

        /* 搜索框样式 */
        .search-box {
            position: relative;
            max-width: 300px;
        }

        .search-box .form-control {
            padding-left: 2.5rem;
            border-radius: 20px;
            border: 1px solid var(--border-color);
        }

        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }

        /* 分页样式 */
        .pagination {
            margin-top: 1.5rem;
        }

        .page-link {
            color: var(--primary-color);
            border: 1px solid var(--border-color);
            padding: 0.5rem 1rem;
        }

        .page-item.active .page-link {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .navbar {
                left: 0;
            }

            .main-content {
                margin-left: 0;
            }

            .sidebar.show {
                transform: translateX(0);
            }
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-light">
    <div class="container-fluid">
        <span class="navbar-brand">抽奖系统管理后台</span>
        <div class="d-flex align-items-center">
            <button class="btn btn-outline-danger" onclick="logout()">
                <i class="fas fa-sign-out-alt me-2"></i>退出登录
            </button>
        </div>
    </div>
</nav>

<!-- 侧边栏 -->
<nav class="sidebar">
    <div class="sidebar-sticky">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="#" data-section="userSection">
                    <i class="fas fa-users"></i>
                    <span>用户管理</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-section="prizeSection">
                    <i class="fas fa-gift"></i>
                    <span>奖品管理</span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-section="recordSection">
                    <i class="fas fa-history"></i>
                    <span>抽奖记录</span>
                </a>
            </li>
        </ul>
    </div>
</nav>

<!-- 主内容区域 -->
<main class="main-content">
    <div class="content-wrapper">
        <!-- 用户管理 -->
        <div id="userSection" class="section">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2 class="mb-0">用户管理</h2>
                <div class="d-flex">
                    <div class="search-box me-3">
                        <i class="fas fa-search"></i>
                        <input type="text" class="form-control" id="userSearch" placeholder="搜索用户...">
                    </div>
                    <button class="btn btn-primary" onclick="showAddUserModal()">
                        <i class="fas fa-plus"></i> 添加用户
                    </button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>公司名称</th>
                        <th>职位</th>
                        <th>手机号</th>
                        <th>邮箱</th>
                        <th>产品类别</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="userTableBody">
                    </tbody>
                </table>
            </div>
            <nav>
                <ul class="pagination justify-content-center" id="userPagination">
                </ul>
            </nav>
        </div>

        <!-- 奖品管理 -->
        <div id="prizeSection" class="section" style="display: none;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">奖品管理</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="input-group me-2">
                        <input type="text" id="prizeSearchInput" class="form-control" placeholder="输入奖品名称搜索">
                        <div class="input-group-append">
                            <button class="btn btn-outline-secondary" type="button" onclick="searchPrizes()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="showAddPrizeModal()">
                        <i class="fas fa-plus"></i> 添加奖品
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-sm">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>奖品名称</th>
                        <th>奖品图片</th>
                        <th>奖品价值</th>
                        <th>库存</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="prizeTableBody">
                    </tbody>
                </table>
            </div>

            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="prizePagination">
                </ul>
            </nav>
        </div>

        <!-- 抽奖记录 -->
        <div id="recordSection" class="section" style="display: none;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">抽奖记录</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="input-group">
                        <input type="text" id="recordSearchInput" class="form-control" placeholder="输入手机号搜索">
                        <div class="input-group-append">
                            <button class="btn btn-outline-secondary" type="button" onclick="searchRecords()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-sm">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>手机号</th>
                        <th>奖品名称</th>
                        <th>奖品价值</th>
                        <th>抽奖时间</th>
                    </tr>
                    </thead>
                    <tbody id="recordTableBody">
                    </tbody>
                </table>
            </div>

            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="recordPagination">
                </ul>
            </nav>
        </div>
    </div>
</main>

<!-- 用户模态框 -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <div class="mb-3">
                        <label class="form-label">姓名</label>
                        <input type="text" class="form-control" id="userName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">公司名称</label>
                        <input type="text" class="form-control" id="companyName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">职位</label>
                        <input type="text" class="form-control" id="position" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">手机号</label>
                        <input type="tel" class="form-control" id="phone" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">产品类别</label>
                        <select class="form-control" id="productCategory" required>
                            <option value="">请选择</option>
                            <option value="医疗器械">医疗器械</option>
                            <option value="农药">农药</option>
                            <option value="医药">医药</option>
                            <option value="化学品">化学品</option>
                            <option value="化妆品">化妆品</option>
                            <option value="危化品">危化品</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 奖品模态框 -->
<div class="modal fade" id="prizeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加奖品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="prizeForm">
                    <div class="mb-3">
                        <label class="form-label">奖品名称</label>
                        <input type="text" class="form-control" id="prizeName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖品价值</label>
                        <input type="number" class="form-control" id="prizeValue" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖品图片</label>
                        <div class="d-flex align-items-center">
                            <input type="file" id="prizeImage" accept="image/*" style="display: none;"
                                   onchange="handleImageUpload(event)">
                            <button type="button" class="btn btn-outline-primary me-2"
                                    onclick="document.getElementById('prizeImage').click()">
                                选择图片
                            </button>
                            <img id="prizeImagePreview" src="" alt=""
                                 style="max-width: 100px; max-height: 100px; display: none;">
                        </div>
                        <input type="hidden" id="prizeImageUrl">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">库存数量</label>
                        <input type="number" class="form-control" id="prizeQuantity" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="savePrize()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<script>
    // 添加全局变量存储域名配置
    let domainConfig = 'https://lottery.starlit.top';


    // 检查登录状态
    if (!localStorage.getItem('isLoggedIn')) {
        window.location.href = '/api/lottery/admin/login';
    }

    // 加载用户数据
    function loadUsers(page = 1) {
        $.get('/api/lottery/user/list', {
            current: page,
            size: 10,
            name: $('#userSearch').val()
        }, function (data) {
            let html = '';
            data.records.forEach(user => {
                html += `
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.name}</td>
                            <td>${user.companyName}</td>
                            <td>${user.position}</td>
                            <td>${user.phone}</td>
                            <td>${user.email || '-'}</td>
                            <td>${user.productCategory}</td>
                            <td>${new Date(user.createTime).toLocaleString()}</td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </td>
                        </tr>
                    `;
            });
            $('#userTableBody').html(html);

            // 分页
            let pagination = '';
            for (let i = 1; i <= data.pages; i++) {
                pagination += `
                        <li class="page-item ${i === data.current ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadUsers(${i})">${i}</a>
                        </li>
                    `;
            }
            $('#userPagination').html(pagination);
        });
    }

    function deleteUser(id) {
        if (confirm('确定要删除这个用户吗？')) {
            $.ajax({
                url: '/api/lottery/user/' + id,
                method: 'DELETE',
                success: function () {
                    loadUsers();
                }
            });
        }
    }

    function logout() {
        localStorage.removeItem('isLoggedIn');
        window.location.href = '/api/lottery/admin/login';
    }

    $('#userSearch').on('input', function () {
        loadUsers(1);
    });

    function showAddUserModal() {
        $('#userForm')[0].reset();
        $('#userModal').modal('show');
    }

    function saveUser() {
        const user = {
            name: $('#userName').val(),
            companyName: $('#companyName').val(),
            position: $('#position').val(),
            phone: $('#phone').val(),
            email: $('#email').val(),
            productCategory: $('#productCategory').val()
        };

        $.ajax({
            url: '/api/lottery/user/submit',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(user),
            success: function (response) {
                $('#userModal').modal('hide');
                loadUsers();
                // 显示成功提示
                alert('用户添加成功');
            },
            error: function (xhr) {
                // 显示错误信息
                let errorMsg = '保存失败';
                try {
                    const response = JSON.parse(xhr.responseText);
                    errorMsg = response.message || errorMsg;
                } catch (e) {
                    console.error('解析错误响应失败:', e);
                }
                alert(errorMsg);
            }
        });
    }

    loadUsers();

    // 显示指定部分
    function showSection(sectionId, event) {
        // 隐藏所有部分
        document.querySelectorAll('.section').forEach(section => {
            section.style.display = 'none';
        });

        // 显示选中的部分
        document.getElementById(sectionId).style.display = 'block';

        // 更新导航链接状态
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });
        event.currentTarget.classList.add('active');

        // 根据不同的部分加载相应的数据
        if (sectionId === 'recordSection') {
            loadRecords();
        } else if (sectionId === 'prizeSection') {
            loadPrizes();
        } else if (sectionId === 'userSection') {
            loadUsers();
        }
    }

    // 页面加载完成后初始化
    $(document).ready(function() {
        // 为导航链接添加点击事件
        $('.nav-link').on('click', function(e) {
            e.preventDefault();
            const sectionId = $(this).attr('data-section');
            showSection(sectionId, e);
        });

        // 默认显示用户管理部分
        showSection('userSection', { currentTarget: $('.nav-link[data-section="userSection"]')[0] });
    });

    // 加载抽奖记录
    function loadRecords(page = 1, phone = '') {
        fetch(`/api/lottery/records?current=${page}&size=10${phone ? '&phone=' + phone : ''}`)
            .then(response => response.json())
            .then(data => {
                const tbody = document.getElementById('recordTableBody');
                tbody.innerHTML = '';

                data.records.forEach(record => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                            <td>${record.id}</td>
                            <td>${record.phone}</td>
                            <td>${record.prizeName}</td>
                            <td>${record.prizeValue}</td>
                            <td>${new Date(record.createTime).toLocaleString()}</td>
                        `;
                    tbody.appendChild(tr);
                });

                // 更新分页
                updateRecordPagination(data.current, data.pages);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('加载抽奖记录失败');
            });
    }

    // 更新抽奖记录分页
    function updateRecordPagination(current, total) {
        const pagination = document.getElementById('recordPagination');
        pagination.innerHTML = '';

        // 上一页
        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${current === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `
                <a class="page-link" href="#" onclick="loadRecords(${current - 1})" ${current === 1 ? 'tabindex="-1"' : ''}>
                    上一页
                </a>
            `;
        pagination.appendChild(prevLi);

        // 页码
        for (let i = 1; i <= total; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === current ? 'active' : ''}`;
            li.innerHTML = `
                    <a class="page-link" href="#" onclick="loadRecords(${i})">${i}</a>
                `;
            pagination.appendChild(li);
        }

        // 下一页
        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${current === total ? 'disabled' : ''}`;
        nextLi.innerHTML = `
                <a class="page-link" href="#" onclick="loadRecords(${current + 1})" ${current === total ? 'tabindex="-1"' : ''}>
                    下一页
                </a>
            `;
        pagination.appendChild(nextLi);
    }

    // 搜索抽奖记录
    function searchRecords() {
        const phone = document.getElementById('recordSearchInput').value.trim();
        loadRecords(1, phone);
    }

    // 加载奖品数据
    function loadPrizes(page = 1) {
        $.get('/api/lottery/prize/list', {
            current: page,
            size: 10,
            name: $('#prizeSearchInput').val()
        }, function (data) {
            let html = '';
            data.records.forEach(prize => {
                html += `
                        <tr>
                            <td>${prize.id}</td>
                            <td>${prize.name}</td>
                            <td><img src="${domainConfig}${prize.image}" alt="${prize.name}" style="max-width: 50px; max-height: 50px;"></td>
                            <td>${prize.value}</td>
                            <td>${prize.count}</td>
                            <td>
                                <button class="btn btn-sm btn-primary me-1" onclick="editPrize(${prize.id})">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deletePrize(${prize.id})">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </td>
                        </tr>
                    `;
            });
            $('#prizeTableBody').html(html);

            // 分页
            let pagination = '';
            for (let i = 1; i <= data.pages; i++) {
                pagination += `
                        <li class="page-item ${i === data.current ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadPrizes(${i})">${i}</a>
                        </li>
                    `;
            }
            $('#prizePagination').html(pagination);
        }).fail(function (error) {
            console.error('加载奖品列表失败:', error);
            alert('加载奖品列表失败');
        });
    }

    // 搜索奖品
    function searchPrizes() {
        loadPrizes(1);
    }

    // 处理图片上传
    function handleImageUpload(event) {
        const file = event.target.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/api/lottery/file/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    $('#prizeImageUrl').val(response);
                    $('#prizeImagePreview').attr('src', domainConfig + response).show();
                },
                error: function () {
                    alert('图片上传失败');
                }
            });
        }
    }

    // 编辑奖品
    function editPrize(id) {
        $.get('/api/lottery/prize/' + id, function (prize) {
            $('#prizeName').val(prize.name);
            $('#prizeValue').val(prize.value);
            $('#prizeImageUrl').val(prize.image);
            $('#prizeImagePreview').attr('src', domainConfig + prize.image).show();
            $('#prizeQuantity').val(prize.count);
            // 添加奖品ID到表单
            $('#prizeForm').data('prizeId', id);
            $('#prizeModal').modal('show');
        });
    }

    // 保存奖品
    function savePrize() {
        const prizeId = $('#prizeForm').data('prizeId');
        const prize = {
            name: $('#prizeName').val(),
            value: $('#prizeValue').val(),
            image: $('#prizeImageUrl').val(),
            count: $('#prizeQuantity').val()
        };

        // 如果是编辑模式，添加ID到请求体
        if (prizeId) {
            prize.id = prizeId;
        }

        const url = '/api/lottery/prize';
        const method = prizeId ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(prize),
            success: function () {
                $('#prizeModal').modal('hide');
                loadPrizes();
                // 清除表单中的奖品ID
                $('#prizeForm').removeData('prizeId');
            },
            error: function () {
                alert('保存失败');
            }
        });
    }

    // 显示添加奖品模态框
    function showAddPrizeModal() {
        $('#prizeForm')[0].reset();
        $('#prizeImagePreview').hide();
        // 清除表单中的奖品ID
        $('#prizeForm').removeData('prizeId');
        $('#prizeModal').modal('show');
    }

    // 删除奖品
    function deletePrize(id) {
        if (confirm('确定要删除这个奖品吗？')) {
            $.ajax({
                url: '/api/lottery/prize/' + id,
                method: 'DELETE',
                success: function () {
                    loadPrizes();
                }
            });
        }
    }
</script>
</body>
</html> 